package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    @Override
    public AddressBook selectDefault() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list.get(0);
    }

    @Override
    public AddressBook selectById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list.get(0);
    }

    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);

    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public void setDefault(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(0)
                .build();
        addressBookMapper.updateById(addressBook);

        addressBook=AddressBook.builder()
                .id(id)
                .isDefault(1)
                .build();
        addressBookMapper.updateById(addressBook);
    }
}
